package com.yuba.front.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuba.common.core.constant.Constants;
import com.yuba.common.core.constant.GlobalConstants;
import com.yuba.common.core.exception.front.FrontException;
import com.yuba.common.core.utils.MapstructUtils;
import com.yuba.common.core.utils.StringUtils;
import com.yuba.common.mybatis.core.page.PageQuery;
import com.yuba.common.mybatis.core.page.TableDataInfo;
import com.yuba.common.redis.utils.RedisUtils;
import com.yuba.common.satoken.utils.LoginHelper;
import com.yuba.front.domain.CollectFishSite;
import com.yuba.front.domain.FishSite;
import com.yuba.front.domain.FrontUser;
import com.yuba.front.domain.Posts;
import com.yuba.front.domain.bo.FrontUserBo;
import com.yuba.front.domain.vo.FrontUserVo;
import com.yuba.front.event.GetUserInfoEvent;
import com.yuba.front.mapper.CollectFishSiteMapper;
import com.yuba.front.mapper.FishSiteMapper;
import com.yuba.front.mapper.FrontUserMapper;
import com.yuba.front.mapper.PostsMapper;
import com.yuba.front.service.IFrontUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 前台用户Service业务层处理
 *
 * @author modakai
 * @date 2024-11-30
 */
@RequiredArgsConstructor
@Service
public class FrontUserServiceImpl implements IFrontUserService {

    private final FrontUserMapper baseMapper;

    private final CollectFishSiteMapper collectFishSiteMapper;
    private final PostsMapper postsMapper;
    private final FishSiteMapper fishSiteMapper;

    /**
     * 查询前台用户
     *
     * @param userId 主键
     * @return 前台用户
     */
    @Override
    public FrontUserVo queryById(Long userId) {
        FrontUserVo result = baseMapper.selectVoById(userId);

        Long collectSiteCount = collectFishSiteMapper.selectCount(new LambdaQueryWrapper<CollectFishSite>().eq(CollectFishSite::getUserId, userId));
        Long postsCount = postsMapper.selectCount(new LambdaQueryWrapper<Posts>().eq(Posts::getUserId, userId));
        Long fishSiteCount = fishSiteMapper.selectCount(new LambdaQueryWrapper<FishSite>().eq(FishSite::getUserId, userId));

        result.setPostsCount(postsCount);
        result.setCollectSiteCount(collectSiteCount);
        result.setFishSiteCount(fishSiteCount);
        return result;
    }

    /**
     * 分页查询前台用户列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 前台用户分页列表
     */
    @Override
    public TableDataInfo<FrontUserVo> queryPageList(FrontUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FrontUser> lqw = buildQueryWrapper(bo);
        Page<FrontUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的前台用户列表
     *
     * @param bo 查询条件
     * @return 前台用户列表
     */
    @Override
    public List<FrontUserVo> queryList(FrontUserBo bo) {
        LambdaQueryWrapper<FrontUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FrontUser> buildQueryWrapper(FrontUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FrontUser> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getUsername()), FrontUser::getUsername, bo.getUsername());
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), FrontUser::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), FrontUser::getEmail, bo.getEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), FrontUser::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增前台用户
     *
     * @param bo 前台用户
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(FrontUserBo bo) {
        FrontUser add = MapstructUtils.convert(bo, FrontUser.class);
        validEntityBeforeSave(add);
        //        if (flag) {
//            bo.setUserId(add.getUserId());
//        }
        return baseMapper.insert(add) > 0;
    }

    /**
     * 修改前台用户
     *
     * @param bo 前台用户
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(FrontUserBo bo) {
        FrontUser update = MapstructUtils.convert(bo, FrontUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FrontUser entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除前台用户信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public boolean isExist(FrontUserBo userBo) {
        return baseMapper.exists(new LambdaQueryWrapper<FrontUser>()
            .eq(FrontUser::getUsername, userBo.getUsername()));
    }

    @Override
    public boolean registerUser(FrontUserBo userBo) {
        userBo.setCreateBy(0L);
        userBo.setUpdateBy(0L);
        FrontUser frontUser = MapstructUtils.convert(userBo, FrontUser.class);
        return baseMapper.insert(frontUser) > 0;
    }

    @Override
    public FrontUserVo loadUserByUsername(String username) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<FrontUser>()
            .eq(FrontUser::getUsername, username));
    }

    @Override
    public Boolean updatePassword(FrontUserBo bo) {
        String key = Constants.PASSWORD_VERIFY_CODE + bo.getUsername();
        String verifyFlag = RedisUtils.getCacheObject(key);

        if (verifyFlag == null || !verifyFlag.equals(Constants.PASSWORD_VERIFY_CODE_SUCCESS)) {
            throw new FrontException("违法修改！！！");
        }

        // 加密密码
        String newPassword = BCrypt.hashpw(bo.getPassword());
        LambdaUpdateWrapper<FrontUser> lqt = new LambdaUpdateWrapper<FrontUser>()
            .eq(FrontUser::getUsername, bo.getUsername())
            .set(FrontUser::getPassword, newPassword);
        boolean b = baseMapper.update(lqt) >= 1;
        if (b) {
            RedisUtils.deleteObject(key);
        }
        return b;
    }

    @Override
    public boolean updateUserAvatar(Long userId, Long ossId) {
        return baseMapper.update(null,
            new LambdaUpdateWrapper<FrontUser>()
                .set(FrontUser::getAvatar, ossId)
                .eq(FrontUser::getUserId, userId)) > 0;
    }

    @Override
    public Boolean bindEmail(String email, String code) {
        // 1 校验邮箱验证码
        String key = GlobalConstants.CAPTCHA_CODE_KEY + email;
        String verifyCode = RedisUtils.getCacheObject(key);
        if (StringUtils.isBlank(verifyCode)) {
            throw new FrontException("user.jcaptcha.expire");
        }
        if (!verifyCode.equals(code)) {
            throw new FrontException("user.jcaptcha.error");
        }
        // 2 绑定邮箱
        LambdaUpdateWrapper<FrontUser> updateWrapper = new LambdaUpdateWrapper<FrontUser>()
            .eq(FrontUser::getUserId, LoginHelper.getUserId())
            .set(FrontUser::getEmail, email);
        int update = baseMapper.update(updateWrapper);
        if (update != 1) {
            throw new FrontException("user.bind.email.error");
        }
        RedisUtils.deleteObject(key);
        return true;
    }

    @EventListener
    private void loadUserByUserId(GetUserInfoEvent event) {
        FrontUserVo userVo = baseMapper.selectVoOne(new LambdaQueryWrapper<FrontUser>()
            .eq(FrontUser::getUserId, event.getUserId()));
        event.setUserVo(userVo);
    }
}
